package com.tx.test.impl;

import com.tx.test.entity.Log;
import com.tx.test.entity.User;
import com.tx.test.mapper.LogMapper;
import com.tx.test.mapper.UserMapper;
import com.tx.test.service.LogService;
import com.tx.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

//实现类
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Resource
	private LogService logService;

	@Override
	@Transactional
//	@Transactional(rollbackFor = Exception.class)
	public void insert() throws Exception {
		method1_Test();
	}


	//模拟转账@Transactional
	private void method1_Test() throws Exception {
		System.out.println(">>>>>>>>>>>进入到业务方法");
		User user = new User();
		user.setName("张三");
		userMapper.insertUser(user);//张三扣减500元
		addPayment();//模拟李四增加500元（检查异常）

	}

	//正常情况下执行
	private void method2_Test() throws Exception {
		System.out.println(">>>>>>>>>>>进入到业务方法");
		User user = new User();
		user.setName("张三");
		userMapper.insertUser(user);

	}

	//有运行时异常的情况
	private void method3_Test() throws Exception {
		System.out.println(">>>>>>>>>>>进入到业务方法");
		User user = new User();
		user.setName("张三");
		userMapper.insertUser(user);
		throw new RuntimeException();
	}


	//事务失效（解决方案@Transactional(rollbackFor = Exception.class)）
	private void method4_Test() throws Exception {
		System.out.println(">>>>>>>>>>>进入到业务方法");
		User user = new User();
		user.setName("张三");
		userMapper.insertUser(user);
		throw  new  Exception();
	}

	//日志数据丢失（解决方案：日志service修改@Transactional(propagation = Propagation.NOT_SUPPORTED)）
	private void method5_Test() throws Exception {
		System.out.println(">>>>>>>>>>>进入到业务方法");
		User user = new User();
		user.setName("张三");
		userMapper.insertUser(user);
		logService.insert(getLogEntity());
		throw new RuntimeException();
	}




	private void addPayment() throws FileNotFoundException {
		FileInputStream in = new FileInputStream("a.txt");


	}

	private Log getLogEntity() {
		Log log = new Log();
		log.setName("业务异常日志记录");
		return log;
	}


}
